package cn.slipi.admin.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import java.util.SortedMap;

/**
 * @author litao
 */
public class SignUtil {


    private static final Logger LOG = LoggerFactory.getLogger(SignUtil.class);

    /**
     * 验证签名
     *
     * @param params
     * @param sign
     * @return
     */
    public static boolean verifySign(SortedMap<String, Object> params, String sign) {
        return verifySign(JSONObject.toJSONString(params), sign);
    }

    /**
     * 验证签名
     *
     * @param params
     * @param sign
     * @return
     */

    public static boolean verifySign(String params, String sign) {
        if (StringUtils.isEmpty(params)) {
            return false;
        }
        String paramsSign = getParamsSign(params);
        if (!sign.equals(paramsSign)) {
            LOG.info("Header Sign : {};Correct Sign : {};Params : {}", sign, paramsSign, params);
        }
        return sign.equals(paramsSign);
    }

    /**
     * 获取签名
     *
     * @param params
     * @return
     */
    public static String getParamsSign(String params) {
        return DigestUtils.md5DigestAsHex(params.getBytes()).toUpperCase();
    }
}